package sk.ogame.realm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sk.ogame.brain.Memory;
import sk.ogame.brain.Overmind;
import sk.ogame.brain.thing.BuildingThing;
import sk.ogame.brain.thing.Thing;
import sk.ogame.entity.Planet;
import sk.ogame.entity.PlanetOverview;
import sk.ogame.realm.entity.BuildView;
import sk.ogame.realm.exception.PlanetNoInfoException;

import java.time.LocalTime;
import java.util.*;

/**
 * @author 支绍昆
 * 2023/3/3
 * 建筑
 **/
@Controller
@RequestMapping("/build")
public class BuildController {

    @Autowired
    private Memory memory;
    @Autowired
    private Overmind overmind;

    @GetMapping
    public String build(Model model) {
        Map<Integer, PlanetOverview> overviewMap = memory.getOverviewMap();
        if (overviewMap.isEmpty()) {
            return "build";
        }

        List<BuildView> result = new ArrayList<>();
        for (Integer key : overviewMap.keySet()) {
            int planetId = overviewMap.get(key).getPid();
            BuildView v = new BuildView();
            v.setPlanetId(planetId);
            v.setName(overviewMap.get(key).getPlanetname());
            try {
                Planet planet = memory.getPlanet(planetId);
                if (Objects.nonNull(planet)) {
                    v.setMetal(planet.getM1());
                    v.setCrystal(planet.getM2());
                    v.setDeuterium(planet.getM3());
                    v.setSolarPlant(planet.getM4());
                    v.setCreateTime(planet.getCreatetime());
                }
            } catch (PlanetNoInfoException ignored) {
            }
            result.add(v);
        }
        result.sort(Comparator.comparing(BuildView::getCreateTime));
        model.addAttribute("buildList", result);
        return "build";
    }

    @ResponseBody
    @PostMapping(value = "levelUp")
    public String levelUp(String planetId, String buildId){
         Thing thing = new BuildingThing(Integer.parseInt(planetId),Integer.parseInt(buildId), BuildingThing.Operate.leveUp);
         overmind.add(thing);
        return LocalTime.now().toString();
    }


}
